import random
import hashlib
import urllib
import http
import json
from config.config import Config
from flask import Flask, request, jsonify

from flask import Blueprint
from utils.expand import timecost

translate_bp = Blueprint('translate', __name__)


@translate_bp.route('/get-language-list', methods=['GET'])
def get_language_list() -> str:
    lang_mapping = {
        # '自动检测': 'auto',
        '中文': 'zh',
        '英语': 'en',
        '粤语': 'yue',
        '文言文': 'wyw',
        '日语': 'jp',
        '韩语': 'kor',
        '法语': 'fra',
        '西班牙语': 'spa',
        '泰语': 'th',
        '阿拉伯语': 'ara',
        '俄语': 'ru',
        '葡萄牙语': 'pt',
        '德语': 'de',
        '意大利语': 'it',
        '希腊语': 'el',
        '荷兰语': 'nl',
        '波兰语': 'pl',
        '保加利亚语': 'bul',
        '爱沙尼亚语': 'est',
        '丹麦语': 'dan',
        '芬兰语': 'fin',
        '捷克语': 'cs',
        '罗马尼亚语': 'rom',
        '斯洛文尼亚语': 'slo',
        '瑞典语': 'swe',
        '匈牙利语': 'hu',
        '繁体中文': 'cht',
        '越南语': 'vie',
    }
    return json.dumps(lang_mapping, ensure_ascii=False)


@translate_bp.route('/translate', methods=['POST'])
@timecost
def transalate_question():
    json_result = {}
    data = request.json
    question = data.get('question')
    target_language = data.get('target_language')

    appid = Config.TRANSLATE_APP_ID
    secretKey = Config.TRANSLATE_SECRET_KEY
    salt = random.randint(32768, 65536)
    q = question
    sign = appid + q + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = '/api/trans/vip/translate'
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + 'auto' + \
            '&to=' + target_language + '&salt=' + str(salt) + '&sign=' + sign
    try:
        httpClient = http.client.HTTPSConnection('fanyi-api.baidu.com')
        httpClient.request('GET', myurl)
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        response_result = result.get('trans_result')[0].get('dst')
        json_result['code'] = 200
        json_result['data'] = response_result
    except Exception as e:
        json_result['code'] = 500
        json_result['data'] = '翻译出现异常'
    return jsonify(json_result)
